package pro.uccs.util;

import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**********************************************************
 * Copyright © 2016,北京世纪奥通科技有限公司
 * All Rights Reserved.
 * 文件名称： RestTemplateFactory.java
 * 摘 要： [简要描述本文件的内容]
 * 初始版本：1.0.0
 * 原 作 者：lichangkang
 * 完成日期： 2018/1/17
 * 当前版本： 1.0.0
 * 作 者：lichangkang
 * 完成日期： 2018/1/17 15:37
 *****************************************************************/
public class RestTemplateFactory {
    private static RestTemplate restTemplate;
    /**
     * .
     */
    private static final int    CONNETIONTIMEOUT = 3000;
    /**
     * .
     */
    private static final int    SOCKETTIMEOUT    = 3000;
    
    /**
     * .
     */
    private RestTemplateFactory() {
    }
    
    public static RestTemplate getNewInstance() {
        if (restTemplate == null) {
            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
            requestFactory.setConnectTimeout(CONNETIONTIMEOUT);
            requestFactory.setReadTimeout(SOCKETTIMEOUT);
            restTemplate = new RestTemplate(requestFactory);
            // 解决中文乱码问题
            List<HttpMessageConverter<?>> converterList = restTemplate
                .getMessageConverters();
            MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
            List<MediaType> mediaTypes = new ArrayList<>();
            mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
            mappingJackson2HttpMessageConverter
                .setSupportedMediaTypes(mediaTypes);
            converterList.add(mappingJackson2HttpMessageConverter);
            StringHttpMessageConverter converter = new StringHttpMessageConverter();
//            mediaTypes.clear();
            mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
            mediaTypes.add(MediaType.TEXT_HTML);
            converter.setSupportedMediaTypes(mediaTypes);
            converterList.add(converter);
        }
        return restTemplate;
    }
    
    // private HttpClientBuilder getHttpClientBuilder(){
    // HttpClientBuilder httpClientBuilder = new HttpClientBuilder();
    // }
}
